#!/usr/bin/python 
# -*- coding: utf-8 -*-

import wx,os
from ctrl.TextPanel import TxtPanel
from model.fileModel import fileModel

'''
Notebook窗口
'''
class FXNoteBook(wx.Notebook):
    def __init__(self,parent,id,startState):
        wx.Notebook.__init__(self,parent,id)
        self.frame=parent
        self.app=wx.GetApp()
        self.panels=[]  #面板
        self.fileList=[] #文件列表
        self.historyList={} #历史文件列表
        self.histroyNum=100 #tab id起始值
        self.encoding='utf-8' #默认编码
        self.state=0  #0 暂定定时保存  1 开启定时保存
        self.startState=startState

        #缓存文件
        self.tmpPath=os.getcwd()+'\\tmp\\'
        if not os.path.exists(self.tmpPath):
            os.mkdir(self.tmpPath)
        self.tmpFile=self.tmpPath+"record"
        self.historyFile=self.tmpPath+"history" #历史文件记录

        #注册分页图标
        imageList = wx.ImageList(20,20)
        imageList.Add(wx.Bitmap(os.getcwd()+'\\icon\\new.png'))
        self.AssignImageList(imageList)

        #事件绑定
        self.Bind( wx.EVT_BOOKCTRL_PAGE_CHANGED, self.changeSelectStatus)  #绑定事件
        self.Bind(wx.EVT_LEFT_DCLICK, self.closePageEvent)  #双击关闭

        #正常窗口
        if startState==0:
            #上次关闭时文件重新打开
            self.startPage()
            
        else: #拆分窗口
            self.state=1


    def closePageEvent(self,event):
        '''
        关闭窗口
        '''
        num=self.GetSelection()
        if not self.panels[num].TXResult.IsEmpty() :
            #新建文件保存
            if self.fileList[num].path=="" :
                dlg = wx.MessageDialog(self,"是否更改保存到文件？","提醒",wx.YES_NO|wx.ICON_QUESTION|wx.CANCEL)
                retCode=dlg.ShowModal()

                if retCode== wx.ID_YES: #是
                    self.frame.OnSave()
                elif retCode==wx.ID_NO: #否
                    pass
                else: #取消
                    return

            #与源文件md5不同报错
            elif os.path.exists(self.tmpPath+self.fileList[num].name) and os.path.exists(self.fileList[num].path) and os.path.getsize(self.tmpPath+self.fileList[num].name)!= os.path.getsize(self.fileList[num].path):
                resultDlg = wx.MessageDialog(self,"文件内容变更是否保留",'提醒',wx.YES_NO|wx.ICON_QUESTION|wx.CANCEL)
                result=resultDlg.ShowModal()
                if result == wx.ID_YES:  #保存
                    self.frame.OnSave()
                elif result == wx.ID_NO: #不保存
                    pass
                else: #取消
                    return

        #删除缓存文件
        if os.path.exists(self.tmpPath+self.fileList[num].name):
            os.remove(self.tmpPath+self.fileList[num].name)

        # 保存记录
        if len(self.fileList[num].path)>0:
            listTmp=[]
            if os.path.exists(self.historyFile):
                with open(self.historyFile,'r',encoding=self.encoding) as read:
                    listTmp = read.readlines()
            
            if self.fileList[num].path not in listTmp:
                with open(self.historyFile,'w',encoding=self.encoding) as read:
                    if len(listTmp)>0:
                        for i,one in enumerate(listTmp):
                            if "," in one and i<10:
                                read.write(one+"\n")    
                        
                    read.write(str(self.histroyNum)+","+self.fileList[num].path)
                    self.historyList[self.histroyNum]=self.fileList[num].path.strip('\n')
                    self.histroyNum+=1

        #移除分页
        self.RemovePage(num)

        del self.panels[num]
        del self.fileList[num]

        #更新文件记录
        self.saveFileList(state=1)

        #同步状态栏
        self.changeSelectStatus(event)

    def splitWin(self):
        '''
        拆分
        '''
        
        if len(self.panels)<=1:
            return None,None
        num=self.GetSelection()
        context=self.panels[self.GetSelection()].TXResult.GetValue()

        #移除分页
        self.RemovePage(num)
        del self.panels[num]

        fileModel=self.fileList[num]
        del self.fileList[num]
        #更新文件记录
        self.saveFileList(state=1)
        #同步状态栏
        self.changeSelectStatus(None)
        return fileModel,context

    def changeSelectStatus(self,event):
        if len(self.panels)>0 :
            #内容改动同步
            #文件未修改时，直接同步
            # 文件修改时，提示保存

            #更改状态
            self.frame.SetStatusText('文件名: '+self.GetPageText(self.GetSelection())+" 编码: "+self.fileList[self.GetSelection()].encode,0)
            self.panels[self.GetSelection()].changeStatus()

    def deleteTmpFile(self,filename):
        '''
        删除临时文件
        '''
        os.remove(self.tmpPath+filename)

    def changeTitle(self,filename):
        '''
        更改标签名
        ''' 
        self.SetPageText(self.GetSelection(),filename)
    
    def getFile(self):
        '''
        获得操作的文件
        '''
        if len(self.fileList)>0:
            return self.fileList[self.GetSelection()]
        else:
            return None

    def getTab(self):
        '''
        获取页面
        '''
        if len(self.panels)>0:
            return self.panels[self.GetSelection()]
        else:
            return None
    
    def changeFileState(self):
        '''
        修改文件是否需要保存
        '''
        if len(self.panels)>0:
            model=self.fileList[self.GetSelection()]
            if not model.save:
                model.save=True
                self.fileList[self.GetSelection()]=model


    def addTab(self,filename,path,encode,context,save,addTmp=0):
        '''
        添加新标签 
            filename:文件名
            path:文件存储路径
            encode:编码
            context:文件内容
            save:是否需要保存
            addTmp:是否为关闭子窗口
        '''
        if path=="" and not filename.endswith(")"):  #新建文件
            tmpFilename=filename
            if self.app.num>0:
                tmpFilename=filename+"("+str(self.app.num)+")"
            self.app.num+=1

            if len(self.fileList)>0:

                state=0
                while True:
                    state=0
                    for i,one in enumerate(self.fileList):
                        if one.name == tmpFilename and one.path == '':
                            tmpFilename=filename+"("+str(self.app.num)+")"
                            self.app.num+=1
                            state=1
                            break
                    if state==0:
                        break
            filename=tmpFilename

        else:  #判断文件是否存在
            if len(self.fileList)>0:
                for i,one in enumerate(self.fileList):
                    if one.name == filename and one.path == path:
                        self.SetSelection(i)
                        wx.MessageBox('文件: '+filename+' 已打开', '消息',wx.OK|wx.ICON_WARNING)
                        return

        model=fileModel(filename,path,encode,save)
        self.fileList.append(model)

        textPanel=TxtPanel(self,-1)
        if context!="":
            textPanel.TXResult.SetValue(context)

        self.panels.append(textPanel)
        self.AddPage(textPanel,filename,imageId=0) #创建新分页
        textPanel.changeFont(self.app.fontSize) #设置字号
        self.SetSelection(len(self.panels)-1) #选择该分页

        if addTmp==0:
            self.saveFileList(state=1)  #更新文件列表记录
    
    def changePageModel(self,model):
        '''
        更新page标题和记录 
        '''
        self.fileList[self.GetSelection()]=model
        self.changeSelectStatus(None)

    def jsonFormat(self):
        '''
        json字符串格式化 
        '''
        if len(self.panels)>0:
            self.panels[self.GetSelection()].jsonFormat()
    
    def startPage(self):
        '''
        读取文件
        '''
        #数据文件记录
        if os.path.exists(self.tmpFile):
            with open(self.tmpFile,'r',encoding=self.encoding) as read:
                dataList = read.readlines()
                
            if len(dataList)>0:
                save=True
                
                # num=0
                for i,one in enumerate(dataList):
                    if "," not in one:
                        continue 

                    if len(one)<=0:
                        continue

                    tmp=one.split(",")
                    if not os.path.exists(os.path.join(self.tmpPath+tmp[0])):
                        continue

                    if tmp[3] == 0:
                        save=False
                    else:
                        save=True
                    
                    if tmp[1]=="":
                        self.app.num+=1
                    
                    model=fileModel(tmp[0],tmp[1],tmp[2],save)
                    self.fileList.append(model)
                    with open(os.path.join(self.tmpPath+tmp[0]),'r',encoding=tmp[2]) as f:
                        context=f.read()

                    textPanel=TxtPanel(self,-1)
                    textPanel.TXResult.SetValue(context)
                    textPanel.changeFont(self.app.fontSize) #设置字号
                    self.AddPage(textPanel,model.name,imageId=0)
                    self.panels.append(textPanel)

                    # print(num)
                    # num+=1
                    if int(tmp[4])==1:
                        self.SetSelection(i)

        if not len(self.panels)>0:
            self.addTab("记事本", "",self.encoding,"",True)            

        #历史文件记录
        if os.path.exists(self.historyFile):
            with open(self.historyFile,'r',encoding=self.encoding) as read:
                dataList = read.readlines()
                if len(dataList)>0:
                    for one in dataList:
                        if "," in one:
                            self.historyList[self.histroyNum]=one.split(",")[1].strip('\n')  #路径
                            self.histroyNum+=1

        #清空缓存目录
        all = os.listdir(self.tmpPath)
        for i in all:
            c_path = os.path.join(self.tmpPath, i)
            if not os.path.isdir(c_path):
                os.remove(c_path)

        self.state=1

    def saveFileList(self,state=0):
        '''
        保存文件列表
        state:0 保存文件内容  1 不保存
        '''
        if len(self.fileList)>0:
            dataList=[]
            if os.path.exists(self.tmpFile):
                with open(self.tmpFile,'r',encoding=self.encoding) as read:
                    dataList = read.readlines()

            with open(self.tmpFile,'w',encoding=self.encoding) as fp:
                selectNum=self.GetSelection()

                keyList=[]
                for i,one in enumerate(self.fileList):
                    keyList.append(one.name+","+one.path)
                    #文件列表记录
                    if i==selectNum:
                        fp.write(one.name+","+one.path+","+one.encode+","+str(int(one.save))+",1"+"\n") #0 false 1 true
                    else:
                        fp.write(one.name+","+one.path+","+one.encode+","+str(int(one.save))+",0"+"\n") #0 false 1 true
                    
                    if state==0:
                        self.saveFileData(self.tmpPath+one.name,one.encode,self.panels[i])
                
                for one in dataList:
                    if "," in one:
                        tmp=one.split(",")
                        if tmp[0]+","+tmp[1] not in keyList:
                             fp.write(one+"\n")


    def removeHistory(self,id):
        '''
        移除指定历史id
        '''
        del self.historyList[id]
        self.saveHistoryData()


    def saveFileData(self,path,encode,pane):
        '''
        保存文件内容
        path:路径
        encode:编码
        pane:分页pane
        '''
        with open(path, mode='w',encoding=encode)  as fileWrite:
            if pane.TXResult.IsEmpty():    
                fileWrite.write("")    
            else:
                fileWrite.write(pane.TXResult.GetValue())

    def saveHistoryData(self):
        '''
        保存历史文件记录
        '''
        with open(self.historyFile,'w',encoding=self.encoding) as read:
            if len(self.historyList)>0:
                for one in self.historyList:
                    read.write(str(one)+','+self.historyList[one]+"\n")
            else:
                read.write("")

    def changeFontSize(self,size):
        '''
        修改字体大小
        '''
        if len(self.panels)>0:
            for i,one in enumerate(self.panels):
                one.changeFont(size)

    def SaveData(self):
        '''
        保存数据
        '''
        if len(self.panels)>0 :
            one=self.fileList[self.GetSelection()]
            pane=self.panels[self.GetSelection()]

            self.saveFileData(self.tmpPath+one.name,one.encode,pane)

    def addTmpFile(self):
        '''
        增加自窗口文件数据到主窗口 
        '''
        if self.startState>0 and len(self.fileList)>0:
            for i,one in enumerate(self.fileList):
                context=self.panels[i].TXResult.GetValue()
                if len(context)>0:
                    self.app.frame.fxnotebook.addTab(one.name,one.path,one.encode,context,False,1)
        
    def saveTmpFile(self):
        '''
        定时任务保存临时文件内容
        '''
        if self.state==0:
            return
        
        #记录所有文件
        if self.state==1:
            self.saveFileList()
            
            #保存打开的历史文件
            self.saveHistoryData()
            self.state=2

